﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using T4Template.Bl;
using T4Template.Dto;
using T4Template.Model;

namespace T4Template.Controller
{
    class CodeGenerateController
    {
         private CodeGenerateBL CodeGenerateBL;

        public CodeGenerateController()
        {
            CodeGenerateBL = new CodeGenerateBL();
        }

        public CreateTemplateResultModel GenerateCode(GenerateCodeModel model)
        {
            CreateTemplateResultModel resultModel = new CreateTemplateResultModel();

            GenerateCodeDto dto = new GenerateCodeDto();
            ClassModelDto classDto = new ClassModelDto();
            classDto.Id = model.ClassModel.Id;
            classDto.Name = model.ClassModel.Name;

            foreach (var attribute in model.ClassModel.GetAttributes())
            {
                AttributeModelDto attributeDto = new AttributeModelDto();
                attributeDto.Id = attribute.Id;
                attributeDto.ClassModel = classDto;
                attributeDto.Name = attribute.Name;
                attributeDto.Display = attribute.Display;
                attributeDto.Search = attribute.Search;
                attributeDto.SearchResult = attribute.SearchResult;
                attributeDto.DataType = attribute.DataType;
                attributeDto.FieldDescription  = attribute.FieldDescription;
                attributeDto.Label  = attribute.Label;
                attributeDto.FieldType  = attribute.FieldType;
                attributeDto.Length = attribute.Length;
                attributeDto.Autokey = attribute.Autokey;
                attributeDto.Nullable = attribute.Nullable;
                attributeDto.Pk = attribute.Pk;
                attributeDto.SeqNo = attribute.SeqNo;
                attributeDto.DisplayLengthInGrid = attribute.DisplayLengthInGrid;
                classDto.AddAttribute(attributeDto);
            }

            dto.ClassModel = classDto;
            dto.PatternType = model.PatternType;
            dto.CodeType = model.CodeType;
            dto.ToDirectory = model.PrimaryOutputDirectory;
            dto.SolutionName = model.SolutionName;
            dto.MvcProjectName = model.MvcProjectName;
            dto.BlProjectName = model.BlProjectName;
            dto.DalProjectName = model.DalProjectName;
            dto.StartupProjectDirectory = model.TemplateDirectory;
            dto.CompleteProjectDirectory = model.CompleteProjectDirectory;

            ActionResultDto<CodeTemplateDto> resultDto = CodeGenerateBL.Generate(dto);
            resultModel.Status = resultDto.Status;
            resultModel.ErrorMessage = resultDto.ErrorMessage;

            return resultModel;
        }
    }
}
